<?php

class PostNewController extends Controller {
    var $name = 'PostNew';
    var $uses = array('Posts', 'Diagram', 'Attachments', 'Sessions', 'Post2category', 'Customfields', 'Customvalues');
    var $components = array('upload', 'diagram', 'space', 'json', 'attachment', 'formatting', 'image');
    var $session_key = array('post_id', 'post2category_id');

    function index() {
        $this->action = 'post_new';
        $this->post_new();
    }

    function post_new($id = 0, $status = null) {
        $this->set('has_category', has_category());
        # check is it from out admin
        $out_url = false;

        if (strpos($this->referer, '/post/')) {
            $out_url = $this->referer;
        }
        if (!empty($this->data) && !empty($this->data['Posts']['upload_session'])) {
            # save post
            if (current_user_can('Post', 'add', $this->data['Post2category']['category_id'])) {
                $session_data = $this->__get_session_data($this->data['Posts']['upload_session']);
                $this->data['Posts']['id'] = $session_data['post_id'];
                if (empty($this->data['Posts']['id'])) {
                    $this->data['Posts']['poster_id'] = ArlicleUser::user_id();
                }
                if (isset($this->data['Posts']['post_status']) && $this->data['Posts']['post_status'] == 2) {
                    $this->data['Posts']['post_status'] = 1;  // get_user_post_status();
                }
                $this->data['Posts']['post_time'] = strtotime($this->data['Posts']['post_time']);
                $this->data['Posts']['post_slug'] = $this->__get_post_slug($this->data['Posts']['post_slug'], $this->data['Posts']['id']);
                $this->Posts->save($this->data);
                $post_id = $this->Posts->get_last_insert_id();
                # save customfields values
                $this->__save_customvalues($post_id);

                if (!empty($_FILES['thumbnail']['name'])) {
                    $uploader = new UploadComponent();
                    $file = $uploader->upload_file($_FILES['thumbnail']);
                    if (!empty($file)) {
                        $file['Attachments']['post_id'] = $post_id;
                        $file['Attachments']['is_thumbnail'] = 1;
                        $this->Attachments->save($file);
                    }
                }
                $this->__save_post2category($this->data['Post2category']['category_id'], $post_id);

                $this->Sessions->del($this->data['Posts']['upload_session']);
                if (!empty($this->referer)) {
                    $redirect = $this->referer . '/edit_post_done';
                } else {
                    $redirect = "/post_new/post_new/$post_id/done";
                }

                if ($out_url) {
                    al_redirect($out_url);
                } else {
                    $this->redirect($redirect);
                }
                exit();
            } else {
                $this->header_notice = __('Published failed, You haven\'t permission.'); 
            }
        }

        $this->set('read_password_status', 'style="display:none"');
        $session_data = null;
        $custom_table = null;
        $thumbnail_view_style = 'display: none;';
        $thumbnail_upload_style = '';

        # get the edit post
        if ($status == 'edit' || $status == 'draft' || $status == 'edit_from_web') {
            if ($status == 'edit' || $status == 'edit_from_web') {
                $this->action = 'edit_post';
            }
            $category_id = $this->__get_category_id_by_post_id($id);
            if (empty($category_id)) {
                error_404();
            }
            $this->Posts->id = $id;
            $data['post_id'] = $id;
            $post_id = $id;
            $data['post2category_id'] = $category_id;
            $session_data = serialize($data);
            $post = $this->Posts->read();
            $this->data['Posts']['post_title'] = attribute_escape($post->post_title);
            $this->data['Posts']['post_content'] = $this->Posts->post_content_editor($post->post_content);
            $this->data['Posts']['post_status'] = $post->post_status;
            $this->data['Posts']['post_time'] = date('Y-m-d H:i', $post->post_time);
            $this->data['Posts']['read_password'] = $post->read_password;
            $this->data['Posts']['post_slug'] = $post->post_slug;

            $post_content = $this->data['Posts']['post_content'];
            $file_list = get_attach_list($id);
            $thumbnail = $this->Attachments->find("post_id='$id' AND is_thumbnail='1'", array('upload_time', 'extra'));
            if (!empty($thumbnail->upload_time)) {
                $thumbnail_view_style = '';
                $thumbnail_upload_style = 'display: none;';
                $this->set('thumbnail_url', Router::get_base() . 'www/attach/' . date('Y/n/j/', $thumbnail->upload_time) . $thumbnail->upload_time . '.' . $thumbnail->extra);
            } else {
                $thumbnail_view_style = 'display:none;';
                $thumbnail_upload_style = '';
                $this->set('thumbnail_url', '');
            }
            $this->set('file_list', $file_list['list']);

            $this->set('file_total_size', $file_list['size']);
            $post_time = $post->post_time;
        } else {
            # post new with the category id
            $post_time = time();
            if (!empty($id)) {
                $category_id = $id;
            } else {
                $category_id = '';
            }

            $post_id = 0;
            $post_content = '';
            $this->data['Posts']['post_status'] = 2;
            $this->data['Posts']['post_time'] = date('Y-m-d H:i');
        }
        # get the category custom fields
        $custom_table = $this->__get_customfields($post_id, $category_id);
        $select_list = get_diagram_as_select(array('selected'=>$category_id));
        $session_id = save_session($session_data);
        $this->set('category_id', $category_id);
        $this->set('thumbnail_view_style', $thumbnail_view_style);
        $this->set('thumbnail_upload_style', $thumbnail_upload_style);
        $this->set('select_list', $select_list);
        $this->set('post_status', true);
        $this->set('post_content', $post_content);
        $this->set('reserve_time', date('Y-m-d H:i', time() + 259200));
        $this->set('upload_session', $session_id);
        $this->set('post_type', 1);
        $this->set('attach', Router::get_base() . 'www/attach/' . date('Y/n/j/', $post_time));
        $this->set('upload_max_filesize', al_get_size(get_option('upload_max_filesize'), 'b'));
        
        # after add a new done
        if ($status == 'done') {
            if (!empty($id)) {
                $this->header_notice = __('Your post has been successfully published.') . ' ' . admin_link(__('View or edit'), "/post_new/post_new/$id/edit?/post_new/post_new/$id/done");
            } else {
                $this->header_notice = __('Your post has been successfully published.');
            }
        }
        $this->set('custom_table', $custom_table);
        
        # set the submenu return url
        if ($out_url) {
            $return_url = '/posts/posts/';
        } else {
            $return_url = $this->referer;
        }
        $this->set('return_url', $return_url);
    }

    function ajax_delete_thumbnail($session_id = null) {
        $this->layout = null;
        $session_data = $this->__get_session_data($session_id);
        $post_id = $session_data['post_id'];
        if (empty($post_id)) {
            return null;
        }

        $thumbnail = $this->Attachments->find("post_id='$post_id' AND is_thumbnail='1'", array('upload_time', 'extra'));
        if (!empty($thumbnail->upload_time)) {
            $this->Attachments->del_all("post_id='$post_id' AND is_thumbnail='1'");
            $Post2category = $this->Post2category->find("post_id='$id'", array('id,category_id'));
            if (empty($Post2category)) {
                error_404();
            }
            $category_id = $Post2category->category_id;
            @unlink(ROOT . 'www/attach/' . date('Y/n/j/', $thumbnail->upload_time) . $thumbnail->upload_time . '.' . $thumbnail->extra);
            echo 'done';
        }
        
    }

    function flash_upload_file() {
        $this->layout = null;
        $session_id = $_POST['SESSION_ID'];
        $session_data = $this->__get_session_data($session_id);

        if (empty($session_data['post_id'])) {
            $this->Posts->save(null);
            $post_id = $this->Posts->get_last_insert_id();
            $session_data['post_id'] = $post_id;
            $this->Sessions->id = $session_id;
            $this->Sessions->save_field('data', serialize($session_data));
        }

        $uploader = new UploadComponent();
        $file = null;
        if (isset($_FILES['Filedata'])) {
            $file = $uploader->upload_file($_FILES['Filedata']);
        }

        if (!empty($file)) {
            $file['Attachments']['post_id'] = $session_data['post_id'];
            $this->Attachments->save($file);
            $attachment_id = $this->Attachments->get_last_insert_id();
        }
        $json_data['src'] = date('Y/n/j/', $file['Attachments']['upload_time']) . $file['Attachments']['upload_time'] . '_0.' . $file['Attachments']['extra'];
        $json_data['filename'] = $file['Attachments']['name'];
        $json_data['id'] = $attachment_id;
        $json = new Services_JSON();
        echo $json->encode($json_data);
    }

    function flash_get_uploaded($session_id = null) {
        $this->layout = null;
        $session_data = $this->__get_session_data($session_id);
        $post_id = $session_data['post_id'];
        if (empty($post_id)) {
            return null;
        }
        $name = $_GET['name'];
        if (!empty($name)) {
            $attachment = $this->Attachments->find("post_id='$post_id' AND name='$name'", array('size', 'width', 'height', 'extra', 'upload_time'));
            if (!empty($attachment)) {
                $result = $name;
                $result .= ' (';
                if (!empty($attachment->width))
                    $result .= $attachment->width . 'x' . $attachment->height . ' / ' . al_get_size($attachment->size);
                else
                    $result .= al_get_size($attachment->size);
                $result .= ')';
                $result .= ' !^|' . $attachment->upload_time . '|' . $attachment->extra;
                if (!empty($attachment->width))
                    $result .= '|' . $attachment->width . '|' . $attachment->height . '|';
                echo 'result=' . base64_encode(trim($result));
            }
        }
    }

    function ajax_get_attach_list($session_id = null) {
        $this->layout = null;
        $session_data = $this->__get_session_data($session_id);
        if (empty($session_data['post_id']))
            die();
        $post_id = $session_data['post_id'];
        $file_list = get_attach_list($post_id);
        echo $file_list['list'];
    }

    function delete_attach($upload_session, $file_lists) {
        $this->layout = null;
        $session_data = $this->__get_session_data($upload_session);
        if (empty($session_data['post_id']))
            die();
        $file_lists = trim($file_lists);
        $file_lists = trim($file_lists, '\'');
        $file_lists = str_replace('%27', '', $file_lists);
        $file_lists = explode('|', $file_lists);
        if (!empty($file_lists)) {
            foreach($file_lists as $file) {
                $file = explode('.', $file);
                $file_name = $file[0];
                if (!empty($file_name)) {
                    if (current_user_can('delete_attach', $file_name)) {
                        $this->Attachments->del_all("upload_time='$file_name'");
                        if (isset($file[1])) {
                            $file_url = ROOT . 'www/attach/' . date("Y/n/j", $file_name) . '/' . $file_name . '.' . $file[1];
                        } else {
                            $file_url = ROOT . 'www/attach/' . date('Y/n/j', $file_name) . '/' . $file_name;
                        }
                        if (file_exists($file_url)) {
                            unlink($file_url);
                        }
                    }
                }
            }
        }
        $file_list = get_attach_list($session_data['post_id']);
        echo $file_list['list'];
    }

    function ajax_save($upload_session = null) {
        $this->layout = null;
        $post['Posts'] = $this->field_sanitize($this->Posts, $_POST);
        $session_data = $this->__get_session_data($upload_session);
        $post['Posts']['id'] = $session_data['post_id'];
        if (empty($session_data['post2category_id'])) {
            $post['Posts']['poster_id'] = ArlicleUser::user_id();
        }

        $post['Posts']['post_time'] = strtotime($post['Posts']['post_time']);
        $post['Posts']['post_slug'] = $this->__get_post_slug($this->data['Posts']['post_slug'], $this->data['Posts']['id']);
        $this->Posts->save($post);
        $post_id = $this->Posts->get_last_insert_id();
        $post_category = $_POST['post_category'];

        $this->__save_post2category($post_category, $post_id);

        $session_data['post_id'] = $post_id;
        $session_data['post2category_id'] = $info['Post2category']['category_id'];
        $this->Sessions->id = $upload_session;
        $this->Sessions->save_field('data', serialize($session_data));

        echo '(' . current_user_draft_count() . ')';
    }

    function ajax_del_session($upload_session = null) {
        $this->layout = null;
        $this->__get_session_data($upload_session);
        $this->Sessions->del($upload_session);
    }

    function ajax_get_customfields($category_id, $upload_session) {
        $this->layout = null;

        $session_data = $this->__get_session_data($upload_session);
        $post_id = $session_data['post_id'];
        $table = $this->__get_customfields($post_id, $category_id);
        echo $table;
    }

    function ajax_star_image($image_name) {
        $this->layout = null;
        $image_name = trim($image_name, '\'');
        $post_id = $this->Attachments->field('post_id', "upload_time='$image_name'");
        $this->Attachments->save_field('star_status', 0, "post_id='$post_id' AND star_status='1'");
        $this->Attachments->save_field('star_status', 1, "upload_time='$image_name'");
        echo $image_name;
    }

    function ajax_cancel_star_image($image_name) {
        $this->layout = null;
        $this->Attachments->save_field('star_status', 0, "upload_time='$image_name'");
    }

    function __get_customfields($post_id, $diagram_id) {
        $table = null;
        $fields = $this->Customfields->find_all("diagram_id='$diagram_id'", '*', "ORDER BY field_order ASC");
        if (!empty($fields)) {
            $table = '';
            foreach($fields as $key => $field) {
                $value = $this->Customvalues->field('meta_value', "post_id='$post_id' AND meta_key='$field->field_key'");
                $table .= '<tr class="finalrow_customfields"><th>' . $field->field_title . '</th><td>';
                $table .= '<textarea name="data[Customvalues][' . $field->field_key . ']" rows="2" cols="50">' . $value . '</textarea>';
                $table .= '</td></tr>';
            }
        }
        return $table;
    }

    function __save_post2category($category_id, $post_id) {
        $data = array();
        $this->Post2category->del_all("post_id='$post_id'");
        $data['Post2category']['post_id'] = $post_id;
        $data['Post2category']['category_id'] = $category_id;
        $this->Post2category->save($data);
    }

    function __save_customvalues($post_id) {
        $this->Customvalues->del_all("post_id='$post_id'");
        $custom_values['Customvalues']['post_id'] = $post_id;
        if (!empty($this->data['Customvalues'])) {
            foreach($this->data['Customvalues'] as $key => $value) {
                $custom_values['Customvalues']['meta_key'] = $key;
                $custom_values['Customvalues']['meta_value'] = $value;
                $this->Customvalues->save($custom_values);
            }
        }
    }

    function __get_category_id_by_post_id($post_id) {
        $Post2category = $this->Post2category->find("post_id='$post_id'", array('id,category_id'));
        if (!empty($Post2category)) {
            return $Post2category->category_id; 
        }
    }

    function __get_post_slug($post_slug = '', $post_id = '', $count = 1) {
        if (!empty($post_slug)) {
            if ($count != 1) {
                $post_slug2 = sprintf($post_slug, $count);
            } else {
                $post_slug2 = $post_slug;
            }
            if (!empty($post_id)) {
                $condition = "post_slug='$post_slug2' AND id!='$post_id'";
            } else {
                $condition = "post_slug='$post_slug2'";
            }
            $post = $this->Posts->find($condition, array('id'));
            if (empty($post)) {
                return $post_slug2;
            } else {
                if ($count == 1) {
                    $post_slug = "{$post_slug}-%s";
                }
                $count++;
                return $this->__get_post_slug($post_slug, $post_id, $count);
            }
        }
        
    }
}

?>
